package com.aiyige.page.globalsearch;

import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Handler;
import android.os.HandlerThread;
import android.os.Looper;
import android.os.Message;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.Editable;
import android.text.InputFilter;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.view.KeyEvent;
import android.view.View;
import android.view.inputmethod.EditorInfo;
import android.widget.EditText;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.aiyige.R;
import com.aiyige.arouter.config.ARouterConfig;
import com.aiyige.base.BaseActivity;
import com.aiyige.base.api.ApiManager;
import com.aiyige.base.api.ResponseCode;
import com.aiyige.model.Keyword;
import com.aiyige.model.UserKeyword;
import com.aiyige.model.task.Task;
import com.aiyige.page.globalsearch.adapter.HistoryHotAdapter;
import com.aiyige.page.globalsearch.adapter.KeywordAssociateAdapter;
import com.aiyige.page.globalsearch.model.HistoryHotItem;
import com.aiyige.page.globalsearch.model.KeywordAssociateItem;
import com.aiyige.track.TrackEvent;
import com.aiyige.track.annotation.Track;
import com.aiyige.utils.AccountUtil;
import com.aiyige.utils.EditTextAutoMoveCursorToEndFocusChangeListener;
import com.aiyige.utils.ErrorUtil;
import com.aiyige.utils.InputNumFilter;
import com.aiyige.utils.ListUtil;
import com.aiyige.utils.RetrofitUtil;
import com.aiyige.utils.ToastX;
import com.aiyige.utils.dialog.LoadingDialog;
import com.alibaba.android.arouter.facade.annotation.Autowired;
import com.alibaba.android.arouter.facade.annotation.Route;
import com.alibaba.android.arouter.launcher.ARouter;
import com.alibaba.fastjson.JSON;
import com.beloo.widget.chipslayoutmanager.ChipsLayoutManager;
import com.chad.library.adapter.base.BaseQuickAdapter;

import net.cachapa.expandablelayout.ExpandableLayout;

import java.util.HashMap;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import okhttp3.ResponseBody;
import retrofit2.Response;

@Track("全局搜索")
@Route(path = ARouterConfig.GlobalSearchPage)
public class GlobalSearchPage extends BaseActivity {
    public static final String TAG = GlobalSearchPage.class.getSimpleName();
    public static final int HANDLE_SEARCH = 1;
    public static final int NEXT = 2;
    @BindView(R.id.inputEt)
    EditText inputEt;
    @BindView(R.id.titleBackBtn)
    View titleBackBtn;
    @BindView(R.id.searchLayout)
    LinearLayout searchLayout;
    @BindView(R.id.searchHistoryRv)
    RecyclerView searchHistoryRv;
    @BindView(R.id.searchHistoryLayout)
    LinearLayout searchHistoryLayout;
    @BindView(R.id.searchHotRv)
    RecyclerView searchHotRv;
    @BindView(R.id.searchHotLayout)
    LinearLayout searchHotLayout;
    @BindView(R.id.historyHotLayout)
    LinearLayout historyHotLayout;
    @BindView(R.id.keywordAssociateRv)
    RecyclerView keywordAssociateRv;
    @BindView(R.id.keywordAssociateLayout)
    FrameLayout keywordAssociateLayout;
    HistoryHotAdapter searchHistoryAdapter;
    HistoryHotAdapter searchHotAdapter;
    KeywordAssociateAdapter keywordAssociateAdapter;
    TextWatcher keywordAssociateTextWatcher;
    Handler mainHandler;
    Handler searchHandler;
    HandlerThread searchThread;
    @BindView(R.id.inputEtClearBtn)
    ImageView inputEtClearBtn;
    TrackEvent trackEvent = new TrackEvent();
    boolean showKeywordAssociate = false;
    @Autowired
    String searchWord = "";

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.page_global_search);
        ButterKnife.bind(this);
        ARouter.getInstance().inject(this);
        inputEt.setText(searchWord);
        inputEt.setSelection(inputEt.getText().length());
        inputEt.requestFocus();
        inputEt.setOnFocusChangeListener(new EditTextAutoMoveCursorToEndFocusChangeListener());
        searchHistoryRv.setLayoutManager(ChipsLayoutManager.newBuilder(this).build());
        searchHotRv.setLayoutManager(ChipsLayoutManager.newBuilder(this).build());
        searchHistoryAdapter = new HistoryHotAdapter();
        searchHistoryAdapter.bindToRecyclerView(searchHistoryRv);
        searchHotAdapter = new HistoryHotAdapter();
        searchHotAdapter.bindToRecyclerView(searchHotRv);
        keywordAssociateRv.setLayoutManager(new LinearLayoutManager(this));
        keywordAssociateAdapter = new KeywordAssociateAdapter();
        keywordAssociateAdapter.bindToRecyclerView(keywordAssociateRv);
        keywordAssociateAdapter.setOnItemClickListener(new BaseQuickAdapter.OnItemClickListener() {
            @Override
            public void onItemClick(BaseQuickAdapter adapter, View view, int position) {
                {
                    Map<String, String> attrs = new HashMap<>();
                    attrs.put("method", "1");
                    trackEvent.sendEvent(GlobalSearchPage.this, TrackEvent.GLOBAL_SEARCH_METHOD, TrackEvent.GLOBAL_SEARCH_METHOD_LABEL, attrs);
                }
                inputEt.clearFocus();
                ARouter.getInstance()
                        .build(ARouterConfig.GlobalTabSearchPage)
                        .withString("searchWord", keywordAssociateAdapter.getItem(position).getKeyword())
                        .withTransition(0, R.anim.activity_still)
                        .navigation(GlobalSearchPage.this, NEXT);
            }
        });

        searchHistoryAdapter.setOnItemClickListener(new BaseQuickAdapter.OnItemClickListener() {
            @Override
            public void onItemClick(BaseQuickAdapter adapter, View view, int position) {
                {
                    Map<String, String> attrs = new HashMap<>();
                    attrs.put("method", "2");
                    trackEvent.sendEvent(GlobalSearchPage.this, TrackEvent.GLOBAL_SEARCH_METHOD, TrackEvent.GLOBAL_SEARCH_METHOD_LABEL, attrs);
                }
                inputEt.clearFocus();
                ARouter.getInstance()
                        .build(ARouterConfig.GlobalTabSearchPage)
                        .withString("searchWord", searchHistoryAdapter.getItem(position).getSearchStr())
                        .withTransition(0, R.anim.activity_still)
                        .navigation(GlobalSearchPage.this, NEXT);
            }
        });
        searchHotAdapter.setOnItemClickListener(new BaseQuickAdapter.OnItemClickListener() {
            @Override
            public void onItemClick(BaseQuickAdapter adapter, View view, int position) {
                {
                    Map<String, String> attrs = new HashMap<>();
                    attrs.put("method", "3");
                    trackEvent.sendEvent(GlobalSearchPage.this, TrackEvent.GLOBAL_SEARCH_METHOD, TrackEvent.GLOBAL_SEARCH_METHOD_LABEL, attrs);
                }
                inputEt.clearFocus();
                ARouter.getInstance()
                        .build(ARouterConfig.GlobalTabSearchPage)
                        .withString("searchWord", searchHotAdapter.getItem(position).getSearchStr())
                        .withTransition(0, R.anim.activity_still)
                        .navigation(GlobalSearchPage.this, NEXT);
            }
        });
        keywordAssociateTextWatcher = new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {

            }

            @Override
            public void afterTextChanged(Editable s) {
                if (s.length() == 0) {
                    inputEtClearBtn.setVisibility(View.INVISIBLE);
                    hideKeywordAssociate();
                    keywordAssociateAdapter.setNewData(null);
                } else {
                    inputEtClearBtn.setVisibility(View.VISIBLE);
                    showKeywordAssociate();
                    doSearch(s.toString());
                }
            }
        };

        mainHandler = new Handler(Looper.getMainLooper());
        searchThread = new HandlerThread(TAG + "SearchThread");
        searchThread.start();
        searchHandler = new Handler(searchThread.getLooper()) {
            @Override
            public void handleMessage(Message msg) {
                switch (msg.what) {
                    case HANDLE_SEARCH:
                        if (isFinishing() || !showKeywordAssociate) return;
                        String searchStr = (String) msg.obj;
                        final List<KeywordAssociateItem> resultList = new LinkedList<>();
                        if (!TextUtils.isEmpty(searchStr)) {
                            try {
                                Response<ResponseBody> response = ApiManager.getService().searchKeywordAssociate(searchStr).execute();
                                if (response.code() != ResponseCode.OK) {
                                    throw new Exception(ErrorUtil.extractMessageFromErrorResponse(response));
                                }
                                String json = RetrofitUtil.getResponseBodyAsString(response);
                                List<Keyword> keywordList = JSON.parseArray(json, Keyword.class);
                                for (Keyword keyword : keywordList) {
                                    resultList.add(KeywordAssociateItem.newBuilder()
                                            .keyword(keyword.getKeyword())
                                            .build());
                                }
                            } catch (Exception e) {

                            }
                        }
                        mainHandler.post(new Runnable() {
                            @Override
                            public void run() {
                                if (isFinishing() || !showKeywordAssociate) return;
                                keywordAssociateAdapter.setNewData(resultList);
                            }
                        });
                        break;
                }
            }
        };
        inputEt.addTextChangedListener(keywordAssociateTextWatcher);
        inputEt.setOnEditorActionListener(new TextView.OnEditorActionListener() {
            @Override
            public boolean onEditorAction(TextView v, int actionId, KeyEvent event) {
                if (actionId == EditorInfo.IME_ACTION_SEARCH) {
                    if (!TextUtils.isEmpty(v.getText().toString())) {
                        {
                            Map<String, String> attrs = new HashMap<>();
                            attrs.put("method", "0");
                            trackEvent.sendEvent(GlobalSearchPage.this, TrackEvent.GLOBAL_SEARCH_METHOD, TrackEvent.GLOBAL_SEARCH_METHOD_LABEL, attrs);
                        }
                        inputEt.clearFocus();
                        ARouter.getInstance()
                                .build(ARouterConfig.GlobalTabSearchPage)
                                .withString("searchWord", v.getText().toString())
                                .withTransition(0, R.anim.activity_still)
                                .navigation(GlobalSearchPage.this, NEXT);
                        return true;
                    }
                }
                return false;
            }
        });
        inputEt.setFilters(new InputFilter[]{new InputNumFilter(30, false)});
        requestData();
    }

    private void doSearch(String searchStr) {
        Message msg = Message.obtain();
        msg.what = HANDLE_SEARCH;
        msg.obj = searchStr;
        searchHandler.removeMessages(HANDLE_SEARCH);
        searchHandler.sendMessage(msg);
    }

    public void requestData() {
        new RequestDataTask().execute();
    }

    @OnClick({R.id.searchBtn, R.id.titleBackBtn, R.id.deleteHistoryBtn, R.id.inputEtClearBtn})
    public void onViewClicked(View v) {
        switch (v.getId()) {
            case R.id.titleBackBtn:
                finish();
                break;
            case R.id.deleteHistoryBtn:
                new AlertDialog.Builder(this)
                        .setMessage(R.string.confirm_delete_all_histroy_key_word)
                        .setPositiveButton(R.string.ok, new DialogInterface.OnClickListener() {
                            @Override
                            public void onClick(DialogInterface dialog, int which) {
                                new DeleteSearchHistoryTask().execute();
                            }
                        })
                        .setNegativeButton(R.string.cancel, null)
                        .create()
                        .show();
                break;
            case R.id.inputEtClearBtn:
                inputEt.setText("");
                break;
            case R.id.searchBtn:
                if (!TextUtils.isEmpty(inputEt.getText().toString())) {
                    {
                        Map<String, String> attrs = new HashMap<>();
                        attrs.put("method", "0");
                        trackEvent.sendEvent(GlobalSearchPage.this, TrackEvent.GLOBAL_SEARCH_METHOD, TrackEvent.GLOBAL_SEARCH_METHOD_LABEL, attrs);
                    }
                    inputEt.clearFocus();
                    ARouter.getInstance()
                            .build(ARouterConfig.GlobalTabSearchPage)
                            .withString("searchWord", inputEt.getText().toString())
                            .withTransition(0, R.anim.activity_still)
                            .navigation(GlobalSearchPage.this, NEXT);
                }
                break;
        }
    }

    @Override
    protected void onDestroy() {
        searchThread.quit();
        super.onDestroy();
    }

    public void showKeywordAssociate() {
        showKeywordAssociate = true;
        keywordAssociateLayout.setVisibility(View.VISIBLE);
    }

    public void hideKeywordAssociate() {
        showKeywordAssociate = false;
        keywordAssociateLayout.setVisibility(View.INVISIBLE);
    }

    public class DeleteSearchHistoryTask extends AsyncTask<Object, Object, Object> {
        LoadingDialog loadingDialog;

        @Override
        protected void onPreExecute() {
            loadingDialog = LoadingDialog.newBuilder()
                    .with(GlobalSearchPage.this)
                    .message(R.string.text_process)
                    .show();
        }

        @Override
        protected Object doInBackground(Object... objects) {
            try {
                Response<ResponseBody> response = ApiManager.getService()
                        .createTask(Task.newBuilder()
                                .name(Task.batchDeleteAllUserKeywords)
                                .build())
                        .execute();
                if (response.code() != ResponseCode.CREATED) {
                    throw new Exception(ErrorUtil.extractMessageFromErrorResponse(response));
                }
                return null;
            } catch (Exception e) {
                return e;
            }
        }

        @Override
        protected void onPostExecute(Object o) {
            loadingDialog.dismiss();
            if (o instanceof Exception) {
                ToastX.show(((Exception) o).getMessage());
            } else {
                searchHistoryLayout.setVisibility(View.GONE);
            }
        }
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        switch (requestCode) {
            case NEXT:
                if (resultCode == RESULT_OK) {
                    keywordAssociateAdapter.setNewData(null);
                    hideKeywordAssociate();
                    inputEt.removeTextChangedListener(keywordAssociateTextWatcher);
                    inputEt.setText(data.getStringExtra(GlobalTabSearchPage.SEARCH_WORD));
                    inputEt.addTextChangedListener(keywordAssociateTextWatcher);
                    inputEt.requestFocus();
                }
                break;
            default:
                super.onActivityResult(requestCode, resultCode, data);
                break;
        }

    }

    public class RequestDataTask extends AsyncTask<Object, Object, Object> {
        //        LoadingDialog loadingDialog;
        List<HistoryHotItem> historyItemList = new LinkedList<>();
        List<HistoryHotItem> hotItemList = new LinkedList<>();

        @Override
        protected void onPreExecute() {
//            loadingDialog = LoadingDialog.newBuilder()
//                    .with(GlobalSearchPage.this)
//                    .show();
        }

        @Override
        protected Object doInBackground(Object... objects) {
            try {
                List<Keyword> hotKeywordList = new LinkedList<>();
                List<UserKeyword> historyKeywordList = new LinkedList<>();
                Response<ResponseBody> response = ApiManager.getService().hotSearchKeyword().execute();
                if (response.code() != ResponseCode.OK) {
                    throw new Exception(ErrorUtil.extractMessageFromErrorResponse(response));
                }
                String json = RetrofitUtil.getResponseBodyAsString(response);
                hotKeywordList.addAll(JSON.parseArray(json, Keyword.class));
                for (Keyword keyword : hotKeywordList) {
                    hotItemList.add(HistoryHotItem.newBuilder()
                            .searchStr(keyword.getKeyword())
                            .build());
                }
                if (AccountUtil.isLogin()) {
                    response = ApiManager.getService().historySearchKeyword(AccountUtil.getCurrentUser().getId()).execute();
                    if (response.code() != ResponseCode.OK) {
                        throw new Exception(ErrorUtil.extractMessageFromErrorResponse(response));
                    }
                    json = RetrofitUtil.getResponseBodyAsString(response);
                    historyKeywordList.addAll(JSON.parseArray(json, UserKeyword.class));
                    for (UserKeyword userKeyword : historyKeywordList) {
                        historyItemList.add(HistoryHotItem.newBuilder()
                                .searchStr(userKeyword.getKeyword())
                                .build());
                    }
                }
                return null;
            } catch (Exception e) {
                return e;
            }
        }

        @Override
        protected void onPostExecute(Object o) {
//            loadingDialog.dismiss();
            if (o instanceof Exception) {
                ToastX.show(((Exception) o).getMessage());
            } else {
                if (ListUtil.isEmpty(hotItemList)) {
                    searchHotLayout.setVisibility(View.VISIBLE);
                } else {
                    searchHotLayout.setVisibility(View.VISIBLE);
                    searchHotAdapter.setNewData(hotItemList);
                }

                if (ListUtil.isEmpty(historyItemList)) {
                    searchHistoryLayout.setVisibility(View.GONE);
                } else {
                    searchHistoryLayout.setVisibility(View.VISIBLE);
                    searchHistoryAdapter.setNewData(historyItemList);
                }
            }
        }
    }
}
